package org.example.Tomcat;

import org.example.Tomcat.Util.RequestAnalysiser;

import javax.servlet.Servlet;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

/**
 * @description:
 * @author: farprt
 * @create: 2023-02-13 15:54
 **/
public class SocketProcessor implements Runnable {

    private Socket socket;
    private Tomcat tomcat;

    public SocketProcessor(Socket socket, Tomcat tomcat) {
        this.socket = socket;
        this.tomcat = tomcat;
    }

    @Override
    public void run() {
        processSocket(socket);
    }

    private void processSocket(Socket socket) {
        // 处理socket连接 按照HTTP协议解析数据
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int length = inputStream.read(bytes);
            ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, length).asReadOnlyBuffer();
            Request request = RequestAnalysiser.analysis(byteBuffer);
            request.setSocket(socket);
            Response response = new Response(request);
//            System.out.println(request.getMethod()+request.getRequestURL()+request.getProtocol());

            String requestUrl = request.getRequestURL().toString();
            requestUrl = requestUrl.substring(1);
            String[] parts = requestUrl.split("/");
            String appName = parts[0];
            Context context = tomcat.getContextMap().get(appName);

            if (parts.length > 1) {
                Servlet servlet = context.getByUrlPattern(parts[1]);
                if (servlet != null) {
                    servlet.service(request, response);
                    response.complete();
                } else {
                    DefaultServlet defaultServlet = new DefaultServlet();
                    defaultServlet.service(request, response);
                    response.complete();
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}